import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

// 定义主题类型
export type Theme = 'default' | 'dark' | 'light' | 'blue';

// 主题列表常量
export const THEMES: readonly Theme[] = ['default', 'dark', 'light', 'blue'] as const;

// 初始状态
const initialState: { currentTheme: Theme } = {
  currentTheme: (() => {
    const savedTheme = localStorage.getItem('app-theme');
    // 验证本地存储的主题是否有效
    if (savedTheme && THEMES.includes(savedTheme as Theme)) {
      return savedTheme as Theme;
    }
    return 'default';
  })()
};

// 创建主题切片
const themeSlice = createSlice({
  name: 'theme',
  initialState,
  reducers: {
    // 切换主题的action
    setTheme: (state, action: PayloadAction<Theme>) => {
      // 验证主题有效性
      if (THEMES.includes(action.payload)) {
        state.currentTheme = action.payload;
        localStorage.setItem('app-theme', action.payload);
      }
    }
  }
});

// 导出action和reducer
export const { setTheme } = themeSlice.actions;
export default themeSlice.reducer;
    